<template>
  <el-dialog width="600px" :visible.sync="isShow" :show-close="false" class="register">
    <div slot="title" class="title">用户注册</div>
    <div slot="footer" class="footer">
      <el-button @click="reset">取消</el-button>
      <el-button type="primary" @click="register_btn">确定</el-button>
    </div>
    <el-form label-width="80px" :model="form" ref="form" :rules="rules">
      <el-form-item label="头像" class="register_logo" prop="avatar">
        <el-upload
          class="avatar-uploader"
          :action="baseUrl + '/uploads'"
          name="image"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload"
        >
          <img v-if="imageUrl" :src="baseUrl+'/'+imageUrl" class="avatar" />
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form-item>
      <el-form-item prop="username" label="昵称">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item prop="email" label="邮箱">
        <el-input v-model="form.email"></el-input>
      </el-form-item>
      <el-form-item prop="phone" label="手机">
        <el-input v-model="form.phone"></el-input>
      </el-form-item>
      <el-form-item prop="password" label="密码">
        <el-input v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item prop="code" label="图形码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.code"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <img :src="baseUrl + code_img" alt class="code_img" @click="click_code" />
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item prop="rcode" label="验证码">
        <el-row>
          <el-col :span="15">
            <el-input v-model="form.rcode"></el-input>
          </el-col>
          <el-col :span="8" :offset="1">
            <el-button @click="code_btn" :disabled="time != 5">
              获取用户验证码
              <span v-if="time != 5">({{ time }}s)</span>
            </el-button>
          </el-col>
        </el-row>
      </el-form-item>
    </el-form>
  </el-dialog>
</template>

<script>
import { getPhoneCode, toRegister } from "@/api/register.js";
export default {
  // 添加侦听器
  watch: {
    isShow(newVal) {
      if (newVal == false) {
        this.$refs.form.resetFields();
        this.imageUrl = "";
      }
    },
  },
  data() {
    return {
      form: {
        username: "", //	是	string	用户名
        phone: "", //	是	string	手机号
        email: "", //	是	string	邮箱
        avatar: "", //	是	string	头像地址
        password: "", //	是	string	密码
        code: "", //图形验证码
        rcode: "", //短信验证码
      },
      rules: {
        avatar: [{ required: true, message: "请上传头像", trigger: "change" }],
        username: [
          { required: true, message: "请输入昵称", trigger: "change" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let email_reg = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(.[a-zA-Z0-9_-])+/;

              if (email_reg.test(value)) {
                return callback();
              } else {
                return callback(new Error("请输入正确的邮箱"));
              }
            },
            trigger: "change",
          },
        ],
        phone: [
          { required: true, message: "请输入手机号", trigger: "change" },
          {
            validator: (rule, value, callback) => {
              let reg = /^1[3|4|5|7|8][0-9]{9}$/;
              0;

              if (reg.test(value)) {
                return callback();
              } else {
                return callback(new Error("请输入正确的手机号"));
              }
            },
            trigger: "change",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "change" },
          {
            min: 6,
            max: 18,
            message: "密码长度在 6 到 18 个字符",
            trigger: "change",
          },
        ],
        code: [{ required: true, message: "请输入图形码", trigger: "change" }],
        rcode: [{ required: true, message: "请输入验证码", trigger: "change" }],
      },
      baseUrl: process.env.VUE_APP_URL,
      isShow: false,
      code_img: "/captcha?type=sendsms",
      imageUrl: "",
      time: 5,
      // disable: false,
    };
  },

  methods: {
    // 上传头像文件
    handleAvatarSuccess(res) {
      console.log(res);
      // this.imageUrl = URL.createObjectURL(file.raw);//获取到的是本地的路径，前面有blob，函数有file参数
      this.imageUrl = res.data.file_path;
      this.form.avatar = res.data.file_path;
      this.$refs.form.validateField(["avatar"]);
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || file.type === "image/png";
      const isLt2M = file.size / 1024 / 1024 < 2;

      if (!isJPG) {
        this.$message.error("上传头像图片只能是 JPG或png 格式!");
      }
      if (!isLt2M) {
        this.$message.error("上传头像图片大小不能超过 2MB!");
      }
      return isJPG && isLt2M;
    },
    // 注册页面的确定按钮事件
    register_btn() {
      this.$refs.form.validate((result) => {
        if (result) {
          toRegister(this.form).then((res) => {
            console.log(res);
            this.$message.success("注册成功");
            this.isShow = false;
          });
        } else {
          this.$message.error("验证失败");
        }
      });
    },
    // 注册页面的取消按钮事件
    reset() {
      this.isShow = false;
      // this.$refs.form.resetFields();
    },
    //点击图片验证码实现切换效果
    click_code() {
      this.code_img = "/captcha?type=sendsms&fnnsf=" + Date.now();
    },
    // 点击获取短信验证码
    code_btn() {
      // this.disable = true;
      let num = 0;
      this.$refs.form.validateField(["phone", "code"], (errorMessage) => {
        if (errorMessage == "") {
          num++;
        }
      });
      if (num == 2) {
        // this.$message.success("验证成功");
        this.time--;
        let timeId = setInterval(() => {
          this.time--;
          if (this.time <= 0) {
            clearInterval(timeId);
            this.time = 5;
            this.disable = false;
          }
        }, 1000);
        // this.$axios({
        //   withCredentials: true,
        //   url: "/sendsms",
        //   method: "post",
        //   data: {
        //     phone: this.form.phone,
        //     code: this.form.code,
        //   },
        // })
        getPhoneCode({
          phone: this.form.phone,
          code: this.form.code,
        })
          .then((res) => {
            console.log(res);
            this.$message.success("获取成功");
            this.form.rcode = res.data.data.captcha;
            // if (res.data.message == "ok") {
            //   this.$message.success("获取成功");
            //   this.form.rcode = res.data.data.captcha;
            // } else {
            //   this.$message.error("图形验证码错误");
            //   this.form.rcode = "";
            // }
          })
          .catch((error) => {
            console.log(error);
            this.time = 5;
            clearInterval(timeId);
            // this.$message.error(error);
            // this.$message.error("图形码错误，请重新输入");
          });
      } else {
        this.$message.error("请输入手机号与图形码");
        // this.disable = false;
      }
    },
  },
  created() {},
};
</script>

<style lang="less">
.register {
  .title {
    height: 53px;
    line-height: 53px;
    background: linear-gradient(to right, #01c5fa, #1395fa);
    color: #fff;
    text-align: center;
    font-size: 14px;
  }
  .el-dialog__header {
    padding: 0;
  }
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
  .register_logo {
    text-align: center;
  }
  .code_img {
    width: 100%;
    height: 40px;
  }
  .footer {
    text-align: center;
  }
}
</style>
